using System;

namespace CodeConsult.Nordic.nRF8001.ApplicationControlInterface
{
    public class AciExchangeMessage
    {
        private int _messageToSendIndex;
        private int _numberOfBytesReceived;

        public byte ReceivedDebugStatus { get; set; }
        public byte MessageLengthToReceive { get; set; }
        public byte[] ReceivedMessage { get; set; }
        public byte[] MessageToSend { get; set; }

        public bool Finished => MessageLengthToReceive <= _numberOfBytesReceived - 2 && MessageToSend.Length == _messageToSendIndex;

        public AciExchangeMessage(byte[] messageToSend)
        {
            MessageToSend = messageToSend;
        }

        public AciExchangeMessage() :
            this(new byte[0])
        {
        }

        public byte GetNextByteToSend()
        {
            if (MessageToSend.Length == 0 || _messageToSendIndex >= MessageToSend.Length)
                return 0x00;

            return MessageToSend[_messageToSendIndex++];
        }

        public byte[] GetNextBytesToSend(int numberOfBytes)
        {
            var res = new byte[numberOfBytes];
            for (var i = 0; i < numberOfBytes; i++)
            {
                res[i] = GetNextByteToSend();
            }

            return res;
        }

        public void SetNextReceivedByte(byte receivedByte)
        {
            if (_numberOfBytesReceived == 0)
            {
                ReceivedDebugStatus = receivedByte;
            }
            else if (_numberOfBytesReceived == 1)
            {
                if (receivedByte > 31)
                {
                    receivedByte = 0;
                }

                MessageLengthToReceive = receivedByte;
                ReceivedMessage = new byte[MessageLengthToReceive];
            }
            else if (_numberOfBytesReceived < MessageLengthToReceive + 2)
            {
                ReceivedMessage[_numberOfBytesReceived - 2] = receivedByte;
            }

            _numberOfBytesReceived++;
        }

        public void SetNextReceivedBytes(byte[] receivedBytes)
        {
            foreach (var receivedByte in receivedBytes)
            {
                SetNextReceivedByte(receivedByte);
            }
        }
    }
}
